package cc.mrbird.febs.utils.task;

import cc.mrbird.febs.accounting.entity.CompanyProject;
import cc.mrbird.febs.accounting.entity.DetailCost;
import cc.mrbird.febs.accounting.entity.Project;
import cc.mrbird.febs.accounting.entity.StandardSubExtra;
import cc.mrbird.febs.accounting.mapper.DetailCostMapper;
import cc.mrbird.febs.accounting.mapper.StandardSubExtraMapper;
import cc.mrbird.febs.accounting.service.ICompanyProjectService;
import cc.mrbird.febs.accounting.service.IDetailCostService;
import cc.mrbird.febs.accounting.service.IProjectService;
import cc.mrbird.febs.accounting.service.IStandardSubExtraService;
import cc.mrbird.febs.business.entity.Business;
import cc.mrbird.febs.business.service.IBusinessService;
import cc.mrbird.febs.utils.CodeConstant;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import javafx.scene.effect.Blend;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;

@Configuration
@EnableScheduling
public class Clean {

    @Resource
    private StandardSubExtraMapper standardSubExtraMapper;
    @Resource
    private DetailCostMapper detailCostMapper;
    @Resource
    private IStandardSubExtraService standardSubExtraService;
    @Resource
    private IDetailCostService detailCostService;
    @Resource
    private IBusinessService businessService;

    @Resource
    private IProjectService projectService;
    @Resource
    private ICompanyProjectService companyProjectService;


    /*
     * @Author HBH
     * @Description 清除business第三方支出(type 6)，cost表重复数据
     * @Date 2022/7/29
     **/
    @PostConstruct
    @Scheduled(cron = "0 0 */23 * * ?") //每天23.00刷新s
    public void clean1() throws Exception {
        LambdaQueryWrapper<Business> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Business::getType, 6);
        queryWrapper.orderByDesc(Business::getId);
        List<Business> businesses = businessService.getBaseMapper().selectList(queryWrapper);
        Set<String> busIds = new HashSet<>();
        List<String> delIds = new ArrayList<>();
        List<String> codes = new ArrayList<>();
        delIds.add("-1");
        codes.add("-1");
        for (Business business : businesses) {
            if (!busIds.contains(business.getName())) {
                busIds.add(business.getName());
            } else {
                delIds.add(business.getId().toString());
                codes.add(business.getCode());
            }
        }
        businessService.removeByIds(delIds);
        LambdaQueryWrapper<DetailCost> del = new LambdaQueryWrapper<>();
        del.in(DetailCost::getDetailSubjectCode, codes);
        detailCostMapper.delete(del);
    }

        /*
     * @Author HBH
     * @Description 清除错误数据
     * @Date 2022/7/29
     **/
    @PostConstruct
    @Scheduled(cron = "0 0 */23 * * ?") //每天23.00刷新
    public void clean() throws Exception {
        CodeConstant.isImport = true;
        List<DetailCost> list = detailCostService.findDetailCosts();
        Set<String> keys = new HashSet<>();
        List<String> removeIds = new ArrayList<>();
        removeIds.add("-1");
        for (DetailCost detailCost : list) {
            String key = detailCost.getCompanyId() + "-" + detailCost.getProjectId() + detailCost.getDetailSubjectCode() + detailCost.getYearMonth();
            if (keys.contains(key)) {
                removeIds.add(detailCost.getId().toString());
            }
            keys.add(key);
        }
        detailCostService.removeByIds(removeIds);
        CodeConstant.isImport = false;
    }

    /*
     * @Author HBH
     * @Description 初始化extra表
     * @Date 2022/7/29
     **/
//    @PostConstruct
//    @Scheduled(cron = "0 0 */23 * * ?") //每天23.00刷新
    public void myTask1() throws Exception {
        standardSubExtraService.remove(new LambdaQueryWrapper<>());
        LambdaQueryWrapper<DetailCost> queryWrapper = new LambdaQueryWrapper<DetailCost>()
                .select(DetailCost::getProjectId, DetailCost::getDetailSubjectCode)
                .gt(DetailCost::getType, 3)
                .groupBy(DetailCost::getProjectId)
                .groupBy(DetailCost::getDetailSubjectCode);
        List<DetailCost> detailCosts = detailCostMapper.selectList(queryWrapper);
        List<Business> businesses = businessService.list();
        Map<String, Long> indexMap = new HashMap<>();
        List<StandardSubExtra> addList = new ArrayList<>();
        for (Business business : businesses) {
            indexMap.put(business.getCode(), business.getId());
        }
        for (DetailCost detailCost : detailCosts) {
            StandardSubExtra standardSubExtra = new StandardSubExtra();
            standardSubExtra.setProjectId(detailCost.getProjectId());
            standardSubExtra.setBusinessId(indexMap.get(detailCost.getDetailSubjectCode()));
            standardSubExtra.setCreateTime(new Date());
            addList.add(standardSubExtra);
        }
        standardSubExtraService.saveBatch(addList);
    }

    /*
     * @Author HBH
     * @Description 初始化company_project表和detailCost表
     **/
//    @PostConstruct
//    @Scheduled(cron = "0 0 */23 * * ?") //每天23.00刷新
    public void init_project_company() throws Exception {
        System.out.println("---------init_project_company-------------");
        List<CompanyProject> addList = new ArrayList<>();
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Project::getIsDeleted, 0);
        List<Project> list = projectService.getBaseMapper().selectList(queryWrapper);
        for (Project project : list) {
            CompanyProject companyProject = new CompanyProject();
            companyProject.setCompanyId(Long.parseLong(project.getCompanyId()));
            companyProject.setProjectId(project.getId());
            addList.add(companyProject);
        }
        companyProjectService.saveBatch(addList);
        System.out.println("project_company表初始化成功");

        // 初始化detail_cost表的company-id
        LambdaQueryWrapper<DetailCost> dQuery = new LambdaQueryWrapper<>();
        List<DetailCost> dList = detailCostMapper.selectList(dQuery);
        for (DetailCost detailCost : dList) {
            for (CompanyProject companyProject : addList) {
                if (Objects.equals(detailCost.getProjectId(), companyProject.getProjectId())) {
                    detailCost.setCompanyId(companyProject.getCompanyId());
                    break;
                }
            }
        }
        detailCostService.updateBatchById(dList);
        System.out.println("detailCost表CompanyId初始化成功");
    }
//
//    /*
//     * @Author HBH
//     * @Description 初始化business表
//     * @Date 2022/7/2
//     **/
//    @PostConstruct
//    @Scheduled(cron = "0 0 */23 * * ?") //每天23.00刷新
//    public void myTask() throws Exception {
//         DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
//         ThreadContext.bind(manager);
//        LambdaQueryWrapper<StandardSubExtra> queryWrapper = new LambdaQueryWrapper<>();
//        List<StandardSubExtra> list = standardSubExtraMapper.selectList(queryWrapper);
//        HashMap<String, StandardSubExtra> map = new HashMap<>();
//        for (StandardSubExtra standardSubExtra : list) {
//            String name = standardSubExtra.getName();
//            name = name.trim();
//            name = name.equals("") ? "~" : name;
//            String key = name + "@" + standardSubExtra.getType();
//            String code = standardSubExtra.getCode();
//            if (!map.containsKey(key)) {
//                map.put(key, standardSubExtra);
//            } else {
//                LambdaQueryWrapper<DetailCost> q1 = new LambdaQueryWrapper<>();
//                q1.eq(DetailCost::getDetailSubjectCode, code);
//                List<DetailCost> detailCosts = detailCostMapper.selectList(q1);
//                if (detailCosts != null) {
//                    for (DetailCost detailCost : detailCosts) {
//                        detailCost.setDetailSubjectCode(map.get(key).getCode());
//                        detailCost.setModifyTime(new Date());
//                        detailCostService.updateById(detailCost);
//                    }
//                }
//                standardSubExtra.setCode(map.get(key).getCode());
//                standardSubExtra.setModifyTime(new Date());
//                standardSubExtra.setModifyBy("hbh");
//                standardSubExtraService.updateById(standardSubExtra);
//            }
//        }
//        map.forEach((key, value) -> {
//            Business business = new Business();
//            business.setName(key.split("@")[0]);
//            business.setType(Integer.parseInt(key.split("@")[1]));
//            business.setCode(value.getCode());
//            business.setStandardMain(value.getStandardMain());
//            business.setOrder(value.getOrder() );
//            business.setCreateTime(new Date());
//            business.setCreateBy("hbh");
//            business.setFatherId(0L);
//            businessService.save(business);
//        });
//        // 更新business_id
//        list = standardSubExtraMapper.selectList(queryWrapper);
//        for (StandardSubExtra standardSubExtra : list) {
//            LambdaQueryWrapper<Business> q2 = new LambdaQueryWrapper<>();
//            q2.eq(Business::getCode, standardSubExtra.getCode());
//            Business business =  businessService.getOne(q2);
//            standardSubExtra.setBusinessId(business.getId());
//            standardSubExtraService.updateById(standardSubExtra);
//        }
//    }
}
